package com.parktech.sun.web.controller.management.contact;

import com.parktech.sun.domain.model.Constants;
import com.parktech.sun.domain.model.addressbook.ContactGroup;
import com.parktech.sun.domain.model.addressbook.ContactMember;
import com.parktech.sun.domain.model.email.EmailSubscription;
import com.parktech.sun.domain.repository.Page;
import com.parktech.sun.domain.service.BaseService;
import com.parktech.sun.domain.service.email.EmailService;
import com.parktech.sun.domain.service.sunhz.ContactGroupService;
import com.parktech.sun.domain.service.sunhz.ContactMemberService;
import com.parktech.sun.web.controller.management.BaseController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * Created by IntelliJ IDEA.
 * User: Administrator
 * Date: 11-1-8
 * Time: 下午2:59
 * To change this template use File | Settings | File Templates.
 */
@Controller
@RequestMapping("/management/contact")
public class ContactMemberController extends BaseController{
    @Autowired
    private ContactMemberService contactMemberService;
    @Autowired
    private ContactGroupService contactGroupService;
    @Autowired
    private EmailService emailService;
    private final String redirectListURL = "redirect:listContactMembers";

    @RequestMapping(value = "/listContactMembers", method = {RequestMethod.GET, RequestMethod.POST})
    public ModelAndView listContactMembers(HttpServletRequest request) {
        Integer currentPageNo = request.getParameter("pageNo") != null ? Integer.parseInt(request.getParameter("pageNo").trim()) : 1;
        ModelAndView modelAndView = new ModelAndView("management/contact/contactMemberList");

        List fieldColumns = new ArrayList();
        List searchValues = new ArrayList();
        if (request.getParameter("searchKeyName") != null) {
            fieldColumns.add("name");
            searchValues.add(request.getParameter("searchKeyName"));
        }
        String[] sortSchemas={"DESC"};
        String[] sortKeys={"company"};

        Page<ContactMember> returnPage = new Page<ContactMember>(Constants.PAGINATION_PAGE_SIZE, currentPageNo);
        returnPage.setTotalCount(contactMemberService.getTotalSizeWithSimilarCondition(ContactMember.class, fieldColumns, searchValues));
        returnPage.setResult(contactMemberService.getPaginationObjectsWithSimilarCondition(ContactMember.class, currentPageNo, Constants.PAGINATION_PAGE_SIZE, fieldColumns, searchValues, sortSchemas, sortKeys));
        for(ContactMember contactMember:returnPage.getResult())
        {
            if( emailService.getByEmail(contactMember.getEmail())!=null)
              contactMember.setSubscribed(true);
        }

        return modelAndView.addObject(returnPage);
    }

    @RequestMapping(value = "/listContactMemberByGroupID", method = RequestMethod.GET)
    public ModelAndView listContactMemberByGroupID(@RequestParam("contactGroupID") Long contactGroupID, HttpServletRequest request) {
        Integer currentPageNo = request.getParameter("pageNo") != null ? Integer.parseInt(request.getParameter("pageNo").trim()) : 1;
        ModelAndView modelAndView = new ModelAndView("management/contact/oneGroupMembersList");

        ContactGroup contactGroup = contactGroupService.getBeanByID(contactGroupID);


        //List fieldColumns = new ArrayList();
        //List searchValues = new ArrayList();
        if (contactGroupID != null)  //@todo:add the jar of jakata.StringUtil to judge is Positive Integer.
        {
          //  fieldColumns.add("contactGroup.id");
            //searchValues.add(contactGroupID);

            Page<ContactMember> returnPage = new Page<ContactMember>(Constants.PAGINATION_PAGE_SIZE, currentPageNo);
           // returnPage.setTotalCount(contactMemberService.getTotalSizeWithSimilarCondition(ContactMember.class, fieldColumns, searchValues));
           // returnPage.setResult(contactMemberService.getPaginationObjectsWithSimilarCondition(ContactMember.class, currentPageNo, Constants.PAGINATION_PAGE_SIZE, fieldColumns, searchValues, null, null));

            returnPage.setTotalCount(contactGroup.getContactMembers().size());
            ContactMember[] contactMemberArray = contactGroup.getContactMembers().toArray(new ContactMember[0]) ;
            List<ContactMember> contactMemberList = new ArrayList<ContactMember>();
            for(ContactMember contactMember:contactMemberArray)
            {
                contactMemberList.add(contactMember);
            }
            returnPage.setResult(contactMemberList);

            return modelAndView.addObject(returnPage);
        } else {
            return modelAndView.addObject(new Page<ContactMember>(Constants.PAGINATION_PAGE_SIZE, currentPageNo));
        }
    }


    //    @ModelAttribute      @RequestParam
    @RequestMapping(value = "/manageContactMember", method = RequestMethod.GET)
    public String manageMember(Model model, HttpServletRequest request) {
        Long contactMemberID = request.getParameter("contactMemberID") != null ? Long.parseLong(request.getParameter("contactMemberID").trim()) : null;
        if (contactMemberID == null)     // request to add the new contact contactMember object
        {
            model.addAttribute(new ContactMember());
        } else       // request to update the certain contactMember object
        {
            ContactMember contactMember = contactMemberService.getBeanByID(contactMemberID);
            String tempGroupIDConcat = "%";
            for(ContactGroup contactGroup:contactMember.getContactGroups())
            {
                tempGroupIDConcat+=contactGroup.getId()+"%";
            }
            contactMember.setTempGroupIDConcat(tempGroupIDConcat);
            model.addAttribute(contactMember);
        }
        return "management/contact/contactMemberManage";
    }

    @RequestMapping(value = "/saveManageMember", method = RequestMethod.POST)
    public String saveManageMember(@ModelAttribute ContactMember contactMember,HttpServletRequest request) {
        Set<ContactGroup> contactGroupSet = new HashSet<ContactGroup>();
        String[] groupIDArray = request.getParameterValues("groupIDArray");  //@RequestParam("groupIDArray") String[] groupIDArray,
        if(groupIDArray!=null)
        {
            for(String groupID:groupIDArray)
            {
                contactMember.getContactGroups().add(contactGroupService.getBeanByID(Long.valueOf(groupID)));
            }
        }
        Long contactMemberID = contactMember.getId();
        contactMemberService.saveOrUpdateBean(contactMember);
        if (contactMemberID == null) {
            // add the success to create message.
            saveSuccessMessage(request,"创建成功！");

        } else {
            // add the success to edit message.
            saveSuccessMessage(request,"修改成功！");
        }
        String tempGroupIDConcat = "%";
        for(ContactGroup contactGroup:contactMember.getContactGroups())
        {
            tempGroupIDConcat+=contactGroup.getId()+"%";
        }
        contactMember.setTempGroupIDConcat(tempGroupIDConcat);
        return "management/contact/contactMemberManage";
    }


    @RequestMapping(value = "/deleteManageMember", method = RequestMethod.GET)
    public String deleteManageMember(@RequestParam("contactMemberID") Long contactMemberID) {
        contactMemberService.removeBean(contactMemberID);
        return redirectListURL;
    }

    @RequestMapping(value = "/deleteManageMembers", method = RequestMethod.POST)
    public String deleteManageMembers(HttpServletRequest request) {
        String[] contactMemberIDArray = request.getParameter("selectedMemberIDArray") == null ? new String[0] : request.getParameter("selectedMemberIDArray").trim().split(",");
        for (String contactMemberID : contactMemberIDArray) {
            contactMemberService.removeBean(Long.valueOf(contactMemberID.trim()));
        }
        return redirectListURL;
    }

    @ModelAttribute("contactGroupMap")
    public Map<Long, String> getAllContactGroupMap() {
        Map<Long, String> contactGroupMap = new TreeMap<Long, String>();
        List<ContactGroup> contactList = contactGroupService.getPaginationObjectsWithSimilarCondition(ContactGroup.class, 1, 6666, null, null, null, null);
        for (ContactGroup contactGroup : contactList) {
            contactGroupMap.put(contactGroup.getId(), contactGroup.getName());
        }
        return contactGroupMap;
    }

     @RequestMapping("/subscription")
    public String apply(@RequestParam("email") String email) {
        EmailSubscription emailSubscription = emailService.getByEmail(email);
        if (emailSubscription == null) {
            emailSubscription = new EmailSubscription();
            emailSubscription.setEmail(email);

            emailService.saveOrUpdateBean(emailSubscription);
        }
        return redirectListURL;
    }


}
